#include "list.h"

void print_error(const char* error_msg)
{
    fprintf(stderr, "Error: %s\n", error_msg);
}

list_t* init_list() {
    list_t* l = (list_t*) malloc(sizeof(list_t));

    if(!l) {
        print_error("Cannot create list");    
        return 0;
    }
    
    return l;
}

void free_list(list_t* l) {
    if(!l) {
        print_error("List is not inialized or null");    
        return;
    }

    free(l);
}

int list_length(list_t* l) {
    if(!l)
    {
        print_error("List is not inialized or null");
        return -1;
    }

    node_t* curr = l->first;
    int count = 0;

    while(curr) {
        count++;
        curr = curr->next;
    }

    return count;
}

int push(list_t* l, void* data) {
    if(!l) {
        print_error("List is not inialized");
        return -1;
    }

    if(!l->first) {
        l->first = (node_t*) malloc(sizeof(node_t));
        l->first->data = data;
        l->first->next = 0;
        return 0;
    }

    node_t* prev = 0;
    node_t* curr = l->first;
    while(curr) {
        prev = curr;
        curr = curr->next;
    }

    curr = (node_t*) malloc(sizeof(node_t));
    curr->data = data;
    curr->next = 0;
    
    prev->next = curr;

    return 0;
}

void* pop(list_t* l) {
    if(!l) {
        print_error("List is not inialized");
        return 0;
    }

    if(!l->first) {
        return 0;
    }

    node_t* prev = 0;
    node_t* curr = l->first;
    while(curr->next) {
       prev = curr;
       curr = curr->next; 
    }

    void *data = curr->data;
    if(prev) {
        prev->next = 0;
    } else {
        l->first = 0;
    }

    free(curr);
    return data;
}
